import { createStore } from 'vuex'

export default createStore({
  state: {
    user: null,
    isAuthenticated: false
  },
  mutations: {
    setUser(state, user) {
      state.user = user
      state.isAuthenticated = true
    },
    logout(state) {
      state.user = null
      state.isAuthenticated = false
    }
  },
  actions: {
    login({ commit }, { username, role }) {
      commit('setUser', { username, role })
    },
    logout({ commit }) {
      commit('logout')
    }
  },
  getters: {
    isAdmin: state => state.user?.role === 'admin',
    isTravel: state => state.user?.role === 'travel',
    isUser: state => state.user?.role === 'user'
  },
    state: {
    user: null
  },
  mutations: {
    setUser(state, user) {
      state.user = user;
      // 同时保存到localStorage以防页面刷新
      localStorage.setItem('user', JSON.stringify(user));
    },
    clearUser(state) {
      state.user = null;
      localStorage.removeItem('user');
    }
  },
  getters: {
    currentUser: state => {
      // 如果state中没有，尝试从localStorage加载
      if (!state.user && localStorage.getItem('user')) {
        state.user = JSON.parse(localStorage.getItem('user'));
      }
      return state.user;
    },
    isAuthenticated: state => {
      return !!state.user;
    }
  }
})